<template>
  <div>
    <Layout ref="layout" type="1" :tabs="tabs" :tabDefault.sync="tabDefault" :total="total" :listQuery="listQuery" @search="getTableData">
      <template #table="{height}">
        <SettingTable v-loading="loading" :height="height" :list="list" :tableData="tableData">
          <template #name="{row}">
            <span class="link">{{row.name}}</span>
          </template>
          <template #num="{row}">
            <span class="link" @click="oper(row,4,true)">{{row.contractNo}}</span>
          </template>
          <template #oper="{row}">
            <span v-if="row.contractState == 2" class="oper" @click="oper(row,1)">签订</span>
            <span v-if="row.contractState == 1" class="oper" @click="oper(row,2)">添加</span>
            <span v-if="row.contractState > 2" class="oper" @click="oper(row,3)">下载</span>
            <span v-if="row.contractState > 2" class="oper" @click="oper(row,4)">续签</span>
            <span v-if="row.contractState == 3" class="oper" @click="oper(row,5)">解除</span>
          </template>
        </SettingTable>
      </template>
    </Layout>
    <el-dialog title="签订" :visible.sync="isDialog1" width="30%">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="选择签订模板">
          <el-select v-model="form.templateId" placeholder="请选择签订模板">
            <el-option v-for="(item,index) in templateList" :key="index" :label="item.value" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialog1 = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <OperationDialog ref="OperationDialog" :formDefaultValue="formDefaultValue" @confirm="onConfirm1" :title="title" :isDialog.sync="isDialog" :formList="formList"></OperationDialog>
  </div>
</template>

<script>
import { HTQS1 } from './config';
import Layout from '../layout/index.vue';
import SettingTable from '../layout/SettingTable.vue';
import OperationDialog from '../PersonnelChanges/OperationDialog';

export default {
  name: 'contractSigned',
  components: { Layout, SettingTable, OperationDialog },
  data() {
    return {
      title: '',
      form: {},

      tableData: [],
      list: HTQS1,
      tabs: [
        { label: '全部', name: '1' },
        { label: '未签订', name: '2' },
      ],

      tabDefault: '1',
      total: 0,
      listQuery: {
        PageSize: 50,
        PageIndex: 1
      },

      loading: false,
      isDialog: false,
      formList: [],
      isDialog1: false,

      templateList: [],
      formDefaultValue: {},
      EmployeeModuleId: '',
      employeeId: '',

    };
  },
  watch: {
    tabDefault: {
      handler() {
        this.tableData = [];
        this.total = 0;
        this.listQuery = { PageSize: 50, PageIndex: 1 };
      }
    }
  },
  methods: {
    async onConfirm1(form) {
      let postData = [];
      for (const [columnid, value] of Object.entries(form)) {
        const obj = this.formList.find(i => i.field === columnid);
        postData.push({ columnid, isCustom: obj.isCustom, [Array.isArray(value) ? 'files' : 'value']: typeof value == 'number' ? value + '' : value });
      }
      
      await this.$api.optionsManage.EmployeeContract(postData, this.EmployeeId).then(res=>{
        if(res.data.status==200){
          this.$message({
          message: '保存成功',
          type: 'success'
        });
        }
      });
      this.$refs.layout.onSearch();
      this.isDialog = false;
    },
    async onConfirm() {
      const htmlToString = (content) => `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body>${content}</body></html>`;
      const { form: { templateId }, EmployeeModuleId, employeeId } = this;
      const { data } = await this.$api.optionsManage.GetTemplateContent({ templateId }); //获取模板内容
      let templateContent = data.data.templateContent;
      const { data: { data: infoList } } = await this.$api.optionsManage.GetAllEnableModuleField(); //获取所有的信息引用
      const infoAll = infoList.reduce((p, c) => p.concat(c.columns), []);
      let DicMap = {};
      const { data: { data: valueList } } = await this.$api.optionsManage.GetContractFieldList({ employeeId: employeeId }); //获取员工字段值列表
      const valueAll = valueList.reduce((p, c) => p.concat(c.fields), []);
      infoAll.map(i => {
        DicMap[i.columnname] = valueAll.find(c => c.fieldId === i.columnid) || {};
      });
      for (const [name, obj] of Object.entries(DicMap)) {
        templateContent = templateContent.replace('${' + name + '}', obj.fieldValue || '');
      }
      const contractContent = htmlToString(templateContent);
      await this.$api.optionsManage.SignContract({ contractContent, employeeModuleId: EmployeeModuleId, templateId });
      this.isDialog1 = false;
      this.$refs.layout.onSearch();
    },
    async getTableData(e) {
      this.loading = true;
      const { pageIndex, pageSize, departments, contractStatus, nameOrJobOrPhone } = e || {};
      console.log(this.$route.query, contractStatus, e);

      const params = { pageIndex: pageIndex || this.listQuery.PageIndex, pageSize: pageSize || this.listQuery.PageSize, departments: departments || [], nameOrJobOrPhone: nameOrJobOrPhone || '', contractStatus: contractStatus ?? Number(this.$route.query.contractStatus || 0) };
      const { data } = await this.$api.optionsManage.GetPageContract(params, this.tabDefault || '1');
      this.tableData = data.data.data;
      this.total = data.data.total;
      this.loading = false;
    },
    async oper({ employeeModuleId: EmployeeModuleId, employeeid: EmployeeId }, command, isDisabled = false) {
      this.EmployeeId = EmployeeId;
      if (command === 1) { //签订
        const { data } = await this.$api.optionsManage.GetSelectTemplate();
        this.templateList = data.data;
        this.isDialog1 = true;
        this.EmployeeModuleId = EmployeeModuleId;
        this.employeeId = EmployeeId;
      }
      if (command === 2) { // 添加
        const obj = { 1: 1, 2:8, 10: 3 , 5: 3  ,8: 4, 11: 7 };
        const value = { 10: 7, 5: 8 };
        const { data } = await this.$api.optionsManage.GetEmpty();    
        const formConfig = data.data.map(i => {
          let fieldItems = null
            if(i.fieldItems&&i.fieldItems.length>0){
              fieldItems = i.fieldItems.map(v=>{
                return ({ fieldName: v.columnName, field: v.columnItemId, fieldType: obj[v.datatype] || '', fileldValue: value[v.datatype] || '', options: v.options})
              })
            }
          console.log(i,'数据')
          return ({ isCustom: i.iscustom, fieldName: i.columnname, field: i.columnid, fieldType: obj[i.datatype] || '', fileldValue: value[i.datatype] || '', options: i.options,fieldItems })
        });
        const formConfigRules = [];
        this.formList = formConfig;
        this.title = '添加合同';
        this.isDialog = true;
        
      }
      if (command === 3) { //下载
        const { data } = await this.$api.optionsManage.GetElectronicContract({ EmployeeModuleId });
        window.open(data.data.fileUrl);
      }
      if (command === 4) { //续签
        const obj = { 1: 1, 2:8, 10: 3, 5: 3, 8: 4, 11: 7 };
        const value = { 10: 7, 5: 8 };
        const { data } = await this.$api.optionsManage.GetEmployeeContract({ EmployeeModuleId }); //空合同模板
        let formDefaultValue = {};
        data.data.map(i => {
          formDefaultValue[i.columnid] = i.datatype == 5 ? Number(i.value) : i.datatype == 11 ? i.files : i.value;
        });
        const formConfig = data.data.map(i => ({ isCustom: i.iscustom, isDisabled, fieldName: i.columnname, field: i.columnid, fieldType: obj[i.datatype] || '', fileldValue: value[i.datatype] || '', options: i.options }));
        const formConfigRules = [];
        this.formList = formConfig;
        this.formDefaultValue = formDefaultValue;
        console.log(formDefaultValue);
        this.title = isDisabled ? '合同详情' : '续签合同';
        this.isDialog = true;
      }
      if (command === 5) { //解除
        await this.$confirm('此操作将永久解除该合同, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).catch(() => { });
        await this.$api.optionsManage.CancelContract({ EmployeeModuleId });
        this.$refs.layout.onSearch();
      }
    }
  },
  created() {
    this.getTableData();
  },
};
</script>

<style lang="less" scoped>
.link {
  text-decoration: underline;
  color: #57b2f2;
  cursor: pointer;
}
</style>
